package org.yuangu.privacyfinance.activities;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.privacy.accountmgr.R;

import org.yuangu.privacyfinance.activities.adapter.EntityListAdapter;
import org.yuangu.privacyfinance.activities.adapter.OnItemClickListener;
import org.yuangu.privacyfinance.activities.adapter.TransactionViewHolder;
import org.yuangu.privacyfinance.activities.dialog.RepeatingTransactionDialog;
import org.yuangu.privacyfinance.activities.helper.SwipeController;
import org.yuangu.privacyfinance.activities.viewmodel.BaseViewModel;
import org.yuangu.privacyfinance.activities.viewmodel.RepeatingTransactionsViewModel;
import org.yuangu.privacyfinance.domain.FinanceDatabase;
import org.yuangu.privacyfinance.domain.model.Account;
import org.yuangu.privacyfinance.domain.model.Category;
import org.yuangu.privacyfinance.domain.model.RepeatingTransaction;
import org.yuangu.privacyfinance.helpers.RepeatingHelper;

import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

public class RepeatingTransactionsActivity extends BaseActivity implements OnItemClickListener<RepeatingTransaction> {
    private RepeatingTransactionsAdapter repeatingTransactionsAdapter;
    private RecyclerView                 recyclerView;
    private TextView                     emptyView;

    @Override
    protected Class<? extends BaseViewModel> getViewModelClass() {
        return RepeatingTransactionsViewModel.class;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContent(R.layout.content_recycler);
        final RepeatingTransactionsViewModel tmpViewModel = (RepeatingTransactionsViewModel) super.viewModel;
        repeatingTransactionsAdapter = new RepeatingTransactionsAdapter(this, tmpViewModel.getRepeatingTransactions());
        repeatingTransactionsAdapter.onItemClick(this);

        addFab(R.layout.fab_add, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openRepeatingTransactionDialog(null);
            }
        });

        recyclerView = findViewById(R.id.recycler_view);
        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(this, 1);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(repeatingTransactionsAdapter);

        SwipeController.SwipeControllerAction deleteAction = new SwipeController.SwipeControllerAction() {
            @Override
            public void onClick(int position) {
                deleteRepeatingTransaction(tmpViewModel.getRepeatingTransactions().getValue().get(position));
            }
            @Override
            public Drawable getIcon() {
                return ContextCompat.getDrawable(RepeatingTransactionsActivity.this, R.drawable.ic_delete_red_24dp);
            }
        };

        final SwipeController swipeController = new SwipeController(this, deleteAction, deleteAction);

        ItemTouchHelper itemTouchhelper = new ItemTouchHelper(swipeController);
        itemTouchhelper.attachToRecyclerView(recyclerView);

        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                swipeController.onDraw(c);
            }
        });

        emptyView = findViewById(R.id.empty_view);
        emptyView.setText(getString(R.string.activity_transactions_empty_list_label));
        tmpViewModel.getRepeatingTransactions().observe(this, new Observer<List<RepeatingTransaction>>() {
            @Override
            public void onChanged(@Nullable List<RepeatingTransaction> repeatingTransactions) {
                if (repeatingTransactions.isEmpty()) {
                    recyclerView.setVisibility(View.GONE);
                    emptyView.setVisibility(View.VISIBLE);
                } else {
                    recyclerView.setVisibility(View.VISIBLE);
                    emptyView.setVisibility(View.GONE);
                }
            }
        });
    }

    @SuppressLint("StringFormatInvalid")
    private void deleteRepeatingTransaction(final RepeatingTransaction transaction) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.repeat_delete_action);
        builder.setMessage(Html.fromHtml(getResources().getString(R.string.repeat_delete_question, transaction.getName())));
        builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                FinanceDatabase.getInstance().repeatingTransactionDao().deleteAsync(transaction);
                Toast.makeText(getBaseContext(), R.string.repeat_deleted_msg, Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        builder.create().show();

    }

    private void openRepeatingTransactionDialog(RepeatingTransaction repeatingTransaction) {
        Bundle args = new Bundle();
        if (repeatingTransaction == null) {

        } else {
            args.putLong(RepeatingTransactionDialog.EXTRA_TRANSACTION_ID, repeatingTransaction.getId());
        }

        RepeatingTransactionDialog dialog = new RepeatingTransactionDialog();
        dialog.setArguments(args);
        dialog.show(getSupportFragmentManager(), "RepeatingTransactionDialog");
    }

    @Override
    public void onItemClick(RepeatingTransaction item) {
        openRepeatingTransactionDialog(item);
    }


    public class RepeatingTransactionsAdapter extends EntityListAdapter<RepeatingTransaction, RepeatingTransactionViewHolder> {
        private LiveData<Map<Long, Account>>  accounts   = FinanceDatabase.getInstance().accountDao().getAllMap();
        private LiveData<Map<Long, Category>> categories = FinanceDatabase.getInstance().categoryDao().getAllMap();


        public RepeatingTransactionsAdapter(BaseActivity context, LiveData<List<RepeatingTransaction>> data) {
            super(context, data);
        }

        @NonNull
        @Override
        public RepeatingTransactionViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View viewItem = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.card_repeating_transaction, parent, false);
            return new RepeatingTransactionViewHolder(viewItem, context);
        }

        @Override
        public void onBindViewHolder(@NonNull final RepeatingTransactionViewHolder holder, int index) {
            super.onBindViewHolder(holder, index);
            final RepeatingTransaction rt = getItem(index);
            holder.setAmount(rt.getAmount());
            holder.setTransactionName(rt.getName());
            holder.setRepeatingText(RepeatingHelper.forgeRepeatingText(context, rt));

            accounts.observe(context, new Observer<Map<Long, Account>>() {
                @Override
                public void onChanged(@Nullable Map<Long, Account> map) {
                    holder.setAccountName(map.get(rt.getAccountId()).getName());
                }
            });

            categories.observe(context, new Observer<Map<Long, Category>>() {
                @Override
                public void onChanged(@Nullable Map<Long, Category> map) {
                    if (rt.getCategoryId() != null) {
                        Category category = map.get(rt.getCategoryId());
                        holder.setCategoryName(category.getName());
                        holder.setCategoryColor(category.getColor());
                    } else {
                        holder.setCategoryName(null);
                        holder.setCategoryColor(null);
                    }
                }
            });
        }
    }
    public class RepeatingTransactionViewHolder extends TransactionViewHolder {
        private TextView tvRepeating;

        public RepeatingTransactionViewHolder(@NonNull View itemView, Context context) {
            super(itemView, context);
            tvRepeating = itemView.findViewById(R.id.textView_repeating);
        }

        public void setRepeatingText(String repeatingText) {
            tvRepeating.setText(repeatingText);
        }
    }

}
